package io.sage.modules.employer.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.plugins.Page;
import com.github.crab2died.ExcelUtils;

import io.sage.common.utils.PageUtils;
import io.sage.modules.employer.dao.employerMapper;
import io.sage.modules.employer.entity.EStudentManager;
import io.sage.modules.employer.entity.Employer;
import io.sage.modules.employer.enums.StudentManagerUseTimeTypeEnum;
import io.sage.modules.employer.service.EmployerService;
import io.sage.modules.exam.enums.ExamEnum;
import io.sage.modules.sys.entity.SysDeptEntity;
import io.sage.modules.sys.entity.SysUserEntity;

@Service("studentService")
public class EmployerServiceImpl implements EmployerService {
	@Autowired
	private employerMapper studentMapper;

	@Value(value="${student.manager-time}")
	private String time;

	@Override
	public PageUtils queryPage(Map<String, Object> params) {
        /*Page<Student> page = this.selectPage(
                new Query<Student>(params).getPage(),
                new EntityWrapper<Student>()
        );*/

		return new PageUtils(null);
	}

	@Override
	public List<Employer> selectStudentLists(Map<String, Object> params) {
		// TODO Auto-generated method stub
		return studentMapper.selectStudentList(params);
	}

	@Override
	public PageUtils selectStudentList(Map<String, Object> params) {
		Integer limit = Integer.parseInt((String)params.get("limit"));
		Integer pageNum = Integer.parseInt((String)params.get("page"));

		Page<Employer> page = new Page<>(pageNum,limit);
		page.setRecords(studentMapper.selectStudentList(page, params));

		return new PageUtils(page);
	}

	@Override
	public Employer selectByPrimaryKey(Integer id) {

		Employer student = studentMapper.selectByPrimaryKey(id);
		//查找数据,应该把密码设置为空.
		student.setUserPwd("");

		return student;
	}

	@Override
	public int insert(Employer record, SysUserEntity user) {

		//如果获取不到值,就返回失败信息-1.
		Integer state=-1;
		if(!"".equals(user.getUserId())){
			//创建人.
			record.setUserId(user.getUserId().intValue());
		}else {
			return state;
		}
		if(!"".equals(user.getDeptId())){
			//设置部门id.
			record.setDeptId(user.getDeptId().intValue());
		}else {
			return state;
		}
		//创建日期.
		record.setCreateTime(new Date());
		//新增数据 数据状态(正常)设置为0.
		record.setDisFlag(ExamEnum.NOTRESULT.getCode());

		record.setUserPwd(DigestUtils.sha256Hex(record.getUserPwd()));

		state = studentMapper.insert(record);

		return state;
	}

	@Override
	public int updateByPrimaryKeySelective(Employer record) {
		if(StringUtils.isBlank(record.getUserPwd())){
			record.setUserPwd(null);
		}else{
			record.setUserPwd(DigestUtils.sha256Hex(record.getUserPwd()));
		}
		int update = studentMapper.updateByPrimaryKeySelective(record);

		return update;
	}

	@Override
	public int deleteBatchIds(Integer[] ids) {

		int delete = studentMapper.deleteBatchIds(ids);

		return delete;
	}

	@Override
	public int insertByBatch(List<Employer> attachmentTables) {
		int insertByBatch = studentMapper.insertByBatch(attachmentTables);
		return insertByBatch;
	}

	@Override
	public List<String> getStudentList(Map<String, Object> params) {

		List<String> getStudentList = studentMapper.getStudentList(params);

		return getStudentList;
	}
	/**
	 * 批量导入学生.
	 */
	@Override
	public Map<String, Object> importStudents(MultipartFile file, Integer unitId, SysUserEntity user, SysDeptEntity dept, Integer majorRoleId, Integer useTimeTypeCode) {
		// 已存在的学生list.
		List<Employer> oldStudentList =new ArrayList<>();
		// 学生时间管理list.
		List<EStudentManager> studentManagerList = new ArrayList<EStudentManager>();

		Map<String, Object> params=new HashMap<String, Object>();

		try {
			List<Employer> readExcel2Objects = ExcelUtils.getInstance().readExcel2Objects(file.getInputStream(), Employer.class);
			//批量添加的没有问题的数据.
			List<Employer> newStudentList =new ArrayList<>();
			//批量添加有问题的数据.
			List<String> studentList = this.getStudentList(params);

			// 成功添加多少条数据.
			int count = 0;
			for(Employer student : readExcel2Objects){
				if(!studentList.contains(student.getUserName())){
					//创建人.
					student.setUserId(user.getUserId().intValue());
					//设置部门id.
					student.setDeptId(user.getDeptId().intValue());
					//创建日期.
					student.setCreateTime(new Date());
					//新增数据 数据状态(正常)设置为0.
					student.setDisFlag(ExamEnum.NOTRESULT.getCode());
					//批量添加的时候，密码默认为六个零.
					if("".equals(student.getUserPwd())){
						student.setUserPwd(DigestUtils.sha256Hex("000000"));
					}else {
						student.setUserPwd(DigestUtils.sha256Hex(student.getUserPwd()));
					}
					//设置学生部门
					student.setEmployeeDeptId(dept.getDeptId().intValue());
					//学生部门的编号
					student.setDeptNumber(dept.getDeptNo());

					newStudentList.add(student);
					count++;
				} else {
					oldStudentList.add(student);
				}
			}
			int insertByBatch = 0 ;

			if(newStudentList != null && newStudentList.size() > 0) {
				// 批量插入学生.
				insertByBatch = this.insertByBatch(newStudentList);
				String batchCode = UUID.randomUUID().toString().replaceAll("-","");
				for (Employer student : newStudentList) {
					// 用户管理. 控制用户过期时间.
					EStudentManager studentManager = new EStudentManager();
					studentManager.setStudentId(student.getId()); // 设置学生id.
					studentManager.setCreateTime(new Date());
					studentManager.setUpdateTime(new Date());
					studentManager.setCreateUser(user.getUserId());
					studentManager.setUpdateUser(user.getUserId());
					studentManager.setDeptId(student.getDeptId());
					studentManager.setDisFlag(student.getDisFlag());
					studentManager.setStopTime(StudentManagerUseTimeTypeEnum.getStopTime(useTimeTypeCode)); // 设置授权使用终止时间.
					studentManager.setBatchCode(batchCode); // 导入批次码.
					studentManagerList.add(studentManager);
				}
			}

			params.put("oldStudentList", oldStudentList);
			params.put("state", insertByBatch);
			params.put("count", count);
			return params;
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return params;
	}

	/**
	 * 密码重置.
	 */
	@Override
	public int reset(Integer id) {
		Employer student = new Employer();
		student.setId(id);

		student.setUserPwd(DigestUtils.sha256Hex("000000"));
		return studentMapper.updateByPrimaryKeySelective(student);
	}

	@Override
	public Employer selectByUserName(String userName) {

		Employer student = studentMapper.selectByUserName(userName);

		return student;
	}

	@Override
	public int updateByState(Employer student) {
		Integer disFlag = student.getDisFlag();
		//如果状态为1停用  则设置改数据为0启动状态.
		if(ExamEnum.PARTYCOMPLET.getCode().equals(disFlag)){
			student.setDisFlag(ExamEnum.NOTRESULT.getCode());
		}
		if(ExamEnum.NOTRESULT.getCode().equals(disFlag)){
			student.setDisFlag(ExamEnum.PARTYCOMPLET.getCode());
		}
		return studentMapper.updateByPrimaryKeySelective(student);
	}

}
